<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends HomeController
{


    //首页 index 方法
    public function index()
    {

        if (empty(session('home'))) {
            $this->display('Login/index');
            exit;
        }

        // 分页信息 
        if (!empty($_GET['p']) && intval($_GET['p']) > 0) {
            $p = intval($_GET['p']);
        } else {
            $p = 1;
        }

        $uq = M('user_question');
        $ut = M('user_topic');
        $q = M('question');

        // $ids = D('user')->where('id='.$_SESSION['home']['id'])->relation('topics')->relation('question')->find();
        // var_dump($ids);

        /*$Model = M('user_topic as ut');
        $list = $Model
        ->field('t.id tid, t.name tname, q.id qid, q.name qname, q.content qcontent,uu.image uuimage, uu.name uuname,uu.id uuid, uq.datetime uqtime, u.id auid, u.name auname, a.id aid, a.filename afile, a.part apart, a.discuss_number adnum,a.zan azan, a.datetime atime')
        ->join('zhihu_topics as t ON ut.topic_id = t.id','LEFT')
        ->join('zhihu_question as q ON t.id = q.topic_id','LEFT')
        ->join('zhihu_user_question as uq ON q.id = uq.question_id','LEFT')
        ->join('zhihu_user as uu ON uq.user_id = uu.id','LEFT')
        ->join('zhihu_answer a ON q.id = a.question_id','LEFT')
        ->join('zhihu_user u ON a.user_id = u.id','LEFT')
        ->where('ut.user_id='.$_SESSION['home']['id'].' AND q.display=1 AND a.display=1')
        ->order('uq.datetime DESC, a.datetime DESC')
        ->page($p, 20)
        ->select();*/



        $Model = M('user_topic as ut');
        $list = $Model
        ->field('t.id tid, t.name tname, t.image timage, q.id qid, q.name qname, q.content qcontent, q.answer_num qanum')
        ->join('zhihu_topics as t ON ut.topic_id = t.id','LEFT')
        ->join('zhihu_question as q ON t.id = q.topic_id','LEFT')
        ->join('zhihu_user_question as uq ON q.id = uq.question_id','LEFT')
        // ->join('zhihu_user as u ON uq.user_id = u.id','INNER')
        ->where('ut.user_id='.$_SESSION['home']['id'].' AND q.display=1')
        ->group('q.id')
        ->page($p, 10)
        ->select();

        //此处再查询每个问题下的一条answer
        $data = array();
        $i = 0;
        foreach ($list as $val) {
            if (!empty($val['qid'])) {
                //查询 回答的数据
                $where = "a.question_id = {$val['qid']} AND u.id = a.user_id";
                $data[$i] = $q->field('u.id auid, u.name auname, a.id aid, a.filename afile, a.part apart, a.discuss_number adnum,a.zan azan, a.datetime atime')->table('zhihu_answer a, zhihu_user u')->order('a.datetime DESC')->where($where)->limit(1)->find();
                if (!empty($data[$i])) {
                    $data[$i] = array_merge($list[$i], $data[$i]);
                } else {
                    $data[$i] = $list[$i];
                }
            }
            $i++;
        }

        usort($data, 'mySort');
        // var_dump($list);
        // var_dump($data);

        $this->assign('p', $p+1);
        $this->assign('data', $data);
        $this->assign('title', '首页 - 知乎');
        $this->display('Index/index');
    }


    //首页提问框ask 查询提问是否存在
    public function ask()
    {
        $model = M('question');
        $where = "name like '%".I('get.name')."%'";
        $data = $model->field('id,name,answer_num')->where($where)->limit(0,10)->order('answer_num DESC')->select();
        $this->assign('data',$data);
        // 将页面内容返回
        return $this->display('Index/ask');
    }

    // 首页提问框  获取话题
    public function gettopic(){
        $model = M('topics');
        $where = "name like '%".I('get.name')."%'";
        $data = $model->field('id,name')->where($where)->limit(0,5)->order(' id DESC')->select();
        // V($data);
        // $this->assign('data',$data);
        // 将页面内容返回
        // return $this->display('Index/ask');
        $this->ajaxReturn($data);
    }

    //首页提问框   添加问题 
    public function addquestion()
    {
        // 验证表单是否为有空
        foreach ($_POST as $v) {
            if ($v == '') {
                $this->error('表单数据有空值, 请重新填写...');
                exit;
            }
        }
        // 实例化问题表 与 话题表
        $ques = M('question');
        $topics = M('topics');
        // 获取数据
        $data = array();
        // 数据过滤, 并整合
        $data['name'] = I('post.name');

        // 判断问题是否已经存在
        if ($ques->where(array('name'=>$data['name']))->select()) {
            $this->error('此问题已经存在...');
        }

        $data['content'] = I('post.content');
        $data['topic_name'] = I('post.topic_name');
        // 查询话题id
        $data['topic_id'] = $topics->getFieldByName($data['topic_name'], 'id');
        // signed 值为1时候 要匿名 设置默认 user_id=1 
        if (isset($_POST['signed']) && ($_POST['signed']== 1)) {
            $data['user_id'] = '1';
            $data['user_name'] = '匿名用户';
        } else {
            $data['user_id'] = $_SESSION['home']['id'];
            $data['user_name'] = $_SESSION['home']['name'];
        }
        // 获取提问时间
        $data['datetime'] = date('Y-m-d H:i:s');
        var_dump($data);
        // 写入数据库
        $id = $ques->add($data);
        if ($id > 0) {
            // 提交成功 自动添加关注
            $attention = M('user_question');
            $arr = array();
            $arr['user_id'] = $_SESSION['home']['id'];
            $arr['question_id'] = $id;
            $arr['datetime'] = $data['datetime'];
            $attention->add($arr);
            // 自动跳转
            $this->redirect('Question/detail','qid='.$id, 0, '提交成功!');
        } else {
            $this->error('提交出错,请核对并重写您的表单信息...');
        }
    }

    /**
     * [quguan 取消关注]
     * @return [type] [无返回值 实现用户对 问题的取消关注]
     */
    public function quguan(){
        $map['user_id'] = $_SESSION['home']['id'];
        $map['question_id'] = $_GET['qid'];
        // var_dump($map);
        // 删除关注
        M('user_question')->where($map)->delete();
    }

    /**
     * [guan 关注]
     * @return [type] [无返回值 实现用户对 问题的关注]
     */
    public function guan(){
        $data=array();
        $data['user_id'] = $_SESSION['home']['id'];
        $data['question_id'] = $_GET['qid'];
        // 不存在则添加
        if(M('user_question')->where($data)->select() == null) {
            $data['datetime'] = date('Y-m-d H:i:s');
            M('user_question')->add($data);
        }
    }

    // 赞同回答...
    public function zan()
    {
        if (!empty($_GET['aid']) && (intval($_GET['aid']) > 0)) {
            $id = intval($_GET['aid']);
            $a = M('answer');
            if($a->where('id='.$id)->setInc('zan', 1)){
                echo 1;
            }
        } else {
            echo 0;
        }
    }

    //取消赞同
    public function quzan()
    {
        if (!empty($_GET['aid']) && intval($_GET['aid']) > 0) {
            $id = intval($_GET['aid']);
            $a = M('answer');
            if($a->where('id='.$id)->setDec('zan', 1)){
                echo 1;
            }
        } else {
            echo 0;
        }
    }

    //感谢 事件ajax 返回
    public function thank()
    {
        if (!empty($_GET['aid']) && intval($_GET['aid']) > 0) {
            $id = intval($_GET['aid']);
            $a = M('answer');
            if($a->where('id='.$id)->setInc('thanks', 1)){
                echo 1;
            }
        } else {
            echo 0;
        }
    }

    // 无帮助 事件ajax 返回
    public function helpless()
    {
        if (!empty($_GET['aid']) && intval($_GET['aid']) > 0) {
            $id = intval($_GET['aid']);
            $a = M('answer');
            if($a->where('id='.$id)->setInc('helpless', 1)){
                echo 1;
            }
        } else {
            echo 0;
        }
    }

    // 举报 事件ajax 返回
    public function report()
    {
        if (!empty($_GET['aid']) && intval($_GET['aid']) > 0) {
            $id = intval($_GET['aid']);
            $a = M('answer');
            if($a->where('id='.$id)->setField('report', 1)){
                echo 1;
            }
        } else {
            echo 0;
        }
    }

    // 答案的回复/评论
    public function getdiscuss()
    {
        if (!empty($_GET['page']) && intval($_GET['page']) > 0) {
            $page = intval($_GET['page']);
        }else{
            $page = 1;
        }

        if (!empty($_GET['aid']) && intval($_GET['aid']) > 0) {
            $aid = intval($_GET['aid']);
            $d = M('discuss');

            $where = "d.answer_id={$aid} AND d.user_id = u.id AND d.display=1";
            $list = $d->table('zhihu_discuss d, zhihu_user u')->field('d.id did, d.content dcontent, d.user_id duid, d.to_user_id tuid, d.zan dzan, d.datetime dtime, u.name uname, u.image uimg')->where($where)->order('d.datetime DESC')->page($page, 10)->select();// 每页10条
            $i = 0;
            foreach ($list as $k => $v) {
                $data = M('user')->field('name, image')->where('id='.$v['tuid'])->select();
                $list[$i]['tuname'] = $data['0']['name'];
                $list[$i]['tuimg'] = $data['0']['image'];
                $i++;
            }
            // V($list);
            $this->ajaxReturn($list);
            // $this->assign('list', $list);
            // echo $this->display('Index/getdiscuss');
        } else {
            echo '暂无评论';

        }
    }

    // 举报评论
    public function discussReport()
    {
        // echo $_POST['did'];
        if (!empty($_POST['did']) && intval($_POST['did']) > 0) {
            $did = intval($_POST['did']);
            $d = M('discuss');
            if($d->where('id='.$did)->setField('report', 1)){
                $this->ajaxReturn(1);
            } else {
                $this->ajaxReturn(0);
            }        
        } else {
            $this->ajaxReturn(0);
        }
    }


    // 添加 评论回复
    public function addReply()
    {

        foreach ($_POST as $val) {
            if ($val == '') {
                $this->ajaxReturn(0);
                exit;
            }
        }
        $data = array();
        $data['content'] = I('post.dcontent');
        $data['answer_id'] = I('post.aid');
        $data['to_user_id'] = I('post.tuid');
        $data['user_id'] = $_SESSION['home']['id'];
        $data['datetime'] = date('Y-m-d H:i:s');

        $d = M('discuss');
        $d->create($data);
        $id = $d->add();
        if ($id) {
            // 在ANSWER表添加评论数量
            M('answer')->where('id='.$data['answer_id'])->setInc('discuss_number', 1);
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }

    // 添加评论
    public function addDiscuss()
    {

        foreach ($_POST as $val) {
            if ($val == '') {
                $this->ajaxReturn(0);
                exit;
            }
        }
        $data = array();
        $data['content'] = I('post.dcontent');

        $data['answer_id'] = I('post.aid');
        $data['user_id'] = $_SESSION['home']['id'];
        $data['datetime'] = date('Y-m-d H:i:s');

        $d = M('discuss');
        $d->create($data);
        $id = $d->add();
        if ($id > 0) {
            // 在ANSWER表添加评论数量
            M('answer')->where('id='.$data['answer_id'])->setInc('discuss_number', 1);
            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }


    // 导航栏搜索框
    public function searchinfo()
    {

        $name = $_GET['name'];
        // $this->ajaxReturn($name);
        // 搜索栏的滚动事件
        if ($name == '') {
            $data = null;
            $this->ajaxReturn($data);
            exit;
        } else {
            $q = M('question');
            $a = M('article');
            $u = M('user');
            // 搜索三个表格
            $where = "name LIKE '%{$name}%'"; // 0是用户
            $data[0] = $u->field('id, name, image')->where($where)->limit(0, 5)->select();

            $where = "display=1 AND title LIKE '%{$name}%'";
            $data[1] = $a->field('id, title')->where($where)->order('datetime')->limit(0, 5)->select(); //1是文章

            $where = "display=1 AND name LIKE '%{$name}%'";
            $data[2] = $q->field('id, name')->where($where)->order('datetime')->limit(0, 5)->select(); //2 是问题

            $this->ajaxReturn($data);
        }
    }


}

